#include "main.h"
uint64_t hcsr04_count = 0;
uint64_t hcsr04_end = 0;
void delay_us(uint32_t udelay)
{
    uint32_t startval, tickn, delays, wait;

    startval = SysTick->VAL;
    tickn = HAL_GetTick();
    // sysc = 主频;  //SystemCoreClock / (1000U / uwTickFreq);
    delays = udelay * 168; // sysc / 1000 * udelay;
    if (delays > startval)
    {
        while (HAL_GetTick() == tickn)
        {
        }
        wait = 168000 + startval - delays;
        while (wait < SysTick->VAL)
        {
        }
    }
    else
    {
        wait = startval - delays;
        while (wait < SysTick->VAL && HAL_GetTick() == tickn)
        {
        }
    }
}
int16_t sonar_mm() // 测距并返回单位为毫米的距离结果
{
    uint32_t Distance, Distance_mm = 0;
    HAL_GPIO_WritePin(Trig_GPIO_Port, Trig_Pin, 1); // 输出高电平
    delay_us(15);
    HAL_GPIO_WritePin(Echo_GPIO_Port, Echo_Pin, 0); // 输出低电平
    while (HAL_GPIO_ReadPin(Echo_GPIO_Port, Echo_Pin) == 0)
        ;             // 等待低电平结束
    hcsr04_count = 0; // 计时清零
    while (HAL_GPIO_ReadPin(Echo_GPIO_Port, Echo_Pin) == 1)
        ;                      // 等待高电平结束
    hcsr04_end = hcsr04_count; // 记录结束时的时间
    if (hcsr04_end < 38)       // 判断是否小于38毫秒，大于38毫秒的就是超时，直接调到下面返回0
    {
        Distance = (hcsr04_end * 346) / 2; // 计算距离，25°C空气中的音速为346m/s
        Distance_mm = Distance / 100;      // 因为上面的time_end的单位是10微秒，所以要得出单位为毫米的距离结果，还得除以100
    }
    return Distance_mm; // 返回测距结果
}

float sonar() // 测距并返回单位为米的距离结果
{
    uint32_t Distance, Distance_mm = 0;
    float Distance_m = 0;
    HAL_GPIO_WritePin(Trig_GPIO_Port, Trig_Pin, 1); // 输出高电平
                                                    // Delay_us(15);                                   // 延时15微秒
    delay_us(20);
    HAL_GPIO_WritePin(Trig_GPIO_Port, Trig_Pin, 0); // 输出低电平
    while (HAL_GPIO_ReadPin(Echo_GPIO_Port, Echo_Pin) == 0)
        ;             // 等待低电平结束
    hcsr04_count = 0; // 计时清零
    while (HAL_GPIO_ReadPin(Echo_GPIO_Port, Echo_Pin) == 1)
        ;                      // 等待高电平结束
    hcsr04_end = hcsr04_count; // 记录结束时的时间
    if (hcsr04_end < 38)
    {
        Distance = (hcsr04_end * 346) / 2;
        Distance_mm = Distance / 100;
        Distance_m = Distance_mm / 1000;
    }
    return Distance_m;
}